package com.qinghe.plant.config;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;

import com.qinghe.plant.util.ManageTool;

public class XmlReader{

	private String path;
	private String file;
	private String key;
	public XmlReader( String file,String key) 
	{
		this.file=file;		
		this.key=key;
		this.path= this.getClass().getProtectionDomain().getCodeSource().getLocation().getFile()+this.file;
		System.out.println("褰撳墠璺緞锛�"+this.path);
	}
	
	//閬嶅巻鍒楄〃
	public <T> List<T> ReadLibrary(Class<T> type)
	{	
		try {
			List<T> lists = new ArrayList<T>();
			DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
			DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
			Document document= documentBuilder.parse(this.path);

			NodeList nodelist= document.getElementsByTagName("Item");	
			for (int i = 0; i < nodelist.getLength(); i++)
			{		
				Map<String, String> map = new HashMap<>();
				NamedNodeMap attributes = nodelist.item(i).getAttributes();				
				for (int j = 0; j < attributes.getLength(); j++) 
					map.put(attributes.item(j).getNodeName(),attributes.item(j).getTextContent());
				
				// map杞被鍨�				
				T obj = type.newInstance();// 閲囩敤鍙嶅皠鍔ㄦ�佸垱寤哄璞�
				BeanInfo beanInfo = Introspector.getBeanInfo(type,Object.class);// 鑾峰彇瀵硅薄瀛楄妭鐮佷俊鎭�,涓嶈Object鐨勫睘鎬�
				PropertyDescriptor[] list = beanInfo.getPropertyDescriptors();// 鑾峰彇bean瀵硅薄涓殑鎵�鏈夊睘鎬�
				for (PropertyDescriptor pd : list) {
					String key = pd.getName(); // 鑾峰彇灞炴�у悕
					Object value = map.get(key); // 鑾峰彇灞炴�у��
					pd.getWriteMethod().invoke(obj, value);// 璋冪敤灞炴�etter()鏂规硶,璁剧疆鍒癹avabean瀵硅薄褰撲腑
				}
				// 鍔犲叆鍒楄〃
				lists.add(obj);
			}
			return lists;
		} catch (Exception e) {
			ManageTool.Log(e.getMessage());
			return null;
		}
	}	
		
	//鑾峰彇鎸囧畾鍏冪礌
	public <T> T ReadLibrary(String id,Class<T> type)
	{
		try {
			DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
			DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
			Document document= documentBuilder.parse(this.path);
			
			//鑾峰彇Map
			Map<String,String> map=new HashMap<>();
			NodeList nodelist= document.getElementsByTagName("Item");
			for (int i = 0; i < nodelist.getLength(); i++) 
			{
				NamedNodeMap attributes = nodelist.item(i).getAttributes();
				for (int j = 0; j < attributes.getLength(); j++) 
					map.put(nodelist.item(i).getNodeName(), nodelist.item(i).getTextContent());					
			}
			
			// map杞被鍨�				
			T obj = type.newInstance();// 閲囩敤鍙嶅皠鍔ㄦ�佸垱寤哄璞�
			BeanInfo beanInfo = Introspector.getBeanInfo(type,Object.class);// 鑾峰彇瀵硅薄瀛楄妭鐮佷俊鎭�,涓嶈Object鐨勫睘鎬�
			PropertyDescriptor[] list = beanInfo.getPropertyDescriptors();// 鑾峰彇bean瀵硅薄涓殑鎵�鏈夊睘鎬�
			for (PropertyDescriptor pd : list) {
				String key = pd.getName(); // 鑾峰彇灞炴�у悕
				Object value = map.get(key); // 鑾峰彇灞炴�у��
				pd.getWriteMethod().invoke(obj, value);// 璋冪敤灞炴�etter()鏂规硶,璁剧疆鍒癹avabean瀵硅薄褰撲腑
			}
			return obj;
		} catch (Exception e) 
		{
			ManageTool.Log(e.getMessage());
			return null;
		}
	}
	
	//澧炲姞鎸囧畾鍏冪礌
	public boolean InserQuestion(Object obj,String id)
	{
		try {
			DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
			DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
			Document document=documentBuilder.parse(this.path);	
			NodeList nodeList=document.getElementsByTagName("Item");
			for(int i=0;i<nodeList.getLength();i++)
			{			
				if(((Element)nodeList.item(i)).getAttribute(this.key).equals(id))
				{
				   ManageTool.Log("宸茬粡娣诲姞浜嗙浉鍚孖D鐨勯璁�");
				   return false;
				}	
			}
			
			// 鍙栧嚭杩欎釜鍏冪礌
			Element element = document.createElement("Item");
			Field[] fields=obj.getClass().getDeclaredFields();
			for (int i = 0; i < fields.length; i++) {
					element.setAttribute(fields[i].getName(),ManageTool.GetValue(fields[i], obj));
			}
            
			Element root=document.getDocumentElement();
			root.appendChild(element);	
			
			//娉ㄦ剰锛歑ML鏂囦欢鏄鍔犺浇鍒板唴瀛樹腑 淇敼涔熸槸鍦ㄥ唴瀛樹腑 ==銆嬪洜姝ら渶瑕佸皢鍐呭瓨涓殑鏁版嵁鍚屾鍒扮鐩樹腑
			Transformer transformer = TransformerFactory.newInstance().newTransformer();//鑾峰彇 TransformerFactory 鐨勬柊瀹炰緥銆� 
			Source source = new DOMSource(document);//鍒涘缓鎵ц浠� Source 鍒� Result 鐨勫鍒剁殑鏂� Transformer銆�
			Result result = new StreamResult(this.path);
			transformer.transform(source, result);//灏� XML==>Source 杞崲涓� Result			
			return true;
			
		} catch (Exception e) {
			ManageTool.Log(e.getMessage());
			return false;
		}
	}
	
	//鍒犻櫎鎸囧畾鍏冪礌
	public boolean DeleteLibrary(String id)
	{
		try {
			DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
			DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
			Document document=documentBuilder.parse(this.path);
			NodeList nodeList=document.getElementsByTagName("Item");
			for(int i=0;i<nodeList.getLength();i++)
			{
				if(((Element) nodeList.item(i)).getAttribute(this.key).equals(id))
				{
					Element root=document.getDocumentElement();
				    root.removeChild(nodeList.item(i));
				    
				    //娉ㄦ剰锛歑ML鏂囦欢鏄鍔犺浇鍒板唴瀛樹腑 淇敼涔熸槸鍦ㄥ唴瀛樹腑 ==銆嬪洜姝ら渶瑕佸皢鍐呭瓨涓殑鏁版嵁鍚屾鍒扮鐩樹腑
					Transformer transformer = TransformerFactory.newInstance().newTransformer();//鑾峰彇 TransformerFactory 鐨勬柊瀹炰緥銆� 
					Source source = new DOMSource(document);//鍒涘缓鎵ц浠� Source 鍒� Result 鐨勫鍒剁殑鏂� Transformer銆�
					Result result = new StreamResult(this.path);
					transformer.transform(source, result);//灏� XML==>Source 杞崲涓� Result	
				   return true;
				}
			}
			return false;
		} catch (Exception e) {
			ManageTool.Log(e.getMessage());
			return false;
		}
	}

	//淇敼鎸囧畾鍏冪礌
	public boolean ALterLibrary(Object obj,String id)
	{
		try {
			DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance();
			DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
			Document document=documentBuilder.parse(this.path);	
			NodeList nodeList=document.getElementsByTagName("Item");
			for(int i=0;i<nodeList.getLength();i++)
			{		
				Element element=(Element)nodeList.item(i);
				if(element.getAttribute(this.key).equals(id))
				{
					Field[] fields=obj.getClass().getDeclaredFields();
					for (int j = 0; j < fields.length; j++)
					{
						if (element.hasAttribute(fields[i].getName()))
							element.setAttribute(fields[j].getName(), ManageTool.GetValue(fields[j], obj));
					}
					
					 //娉ㄦ剰锛歑ML鏂囦欢鏄鍔犺浇鍒板唴瀛樹腑 淇敼涔熸槸鍦ㄥ唴瀛樹腑 ==銆嬪洜姝ら渶瑕佸皢鍐呭瓨涓殑鏁版嵁鍚屾鍒扮鐩樹腑
					Transformer transformer = TransformerFactory.newInstance().newTransformer();//鑾峰彇 TransformerFactory 鐨勬柊瀹炰緥銆� 
					Source source = new DOMSource(document);//鍒涘缓鎵ц浠� Source 鍒� Result 鐨勫鍒剁殑鏂� Transformer銆�
					Result result = new StreamResult(this.path);
					transformer.transform(source, result);//灏� XML==>Source 杞崲涓� Result	
				   return true;
				}		
			}
			return false;
		} catch (Exception e) {
			ManageTool.Log(e.getMessage());
			return false;
		}
	}
}
